#!/bin/bash

echo "🚀 简化版部署脚本..."

# 停止现有进程
echo "📛 停止现有进程..."
pkill -f "node.*dist/main" 2>/dev/null || true
pkill -f "next start" 2>/dev/null || true

# 构建项目
echo "🔨 构建后端..."
cd /Users/zyu/leo/ignite-fun/backend
npm run build

echo "🔨 构建前端..."
cd /Users/zyu/leo/ignite-fun/frontend
npm run build

# 创建日志目录
mkdir -p /Users/zyu/leo/ignite-fun/logs

# 启动服务
echo "🚀 启动后端服务..."
cd /Users/zyu/leo/ignite-fun/backend
PORT=7172 nohup npm run start:prod > ../logs/backend.log 2>&1 &
BACKEND_PID=$!
echo "后端启动，PID: $BACKEND_PID"

echo "🚀 启动前端服务..."
cd /Users/zyu/leo/ignite-fun/frontend
PORT=7171 nohup npm start > ../logs/frontend.log 2>&1 &
FRONTEND_PID=$!
echo "前端启动，PID: $FRONTEND_PID"

# 等待服务启动
sleep 5

# 测试服务
echo "🧪 测试服务..."
echo "后端健康检查:"
curl -s http://localhost:7172/api/health || echo "后端服务可能还在启动中..."

echo ""
echo "✅ 部署完成！"
echo "后端PID: $BACKEND_PID"
echo "前端PID: $FRONTEND_PID"
echo ""
echo "检查服务状态:"
echo "  - 后端日志: tail -f /Users/zyu/leo/ignite-fun/logs/backend.log"
echo "  - 前端日志: tail -f /Users/zyu/leo/ignite-fun/logs/frontend.log"
echo "  - 后端进程: ps aux | grep $BACKEND_PID"
echo "  - 前端进程: ps aux | grep $FRONTEND_PID"
